<?php
/**
*
*产品搜索，默认仅搜索产品
*
*/
class SearchAction extends Action{
	
	public function formatWords($words){
		return $words = array_filter(explode(' ', trim($words)));
	}

	// 转三维产品数组为二维数组
	public function change2array($data){
		$one_way = array();
		foreach ($data as $key => $value) {
			$one_way[$key] = $value['id'];
		};

		return $one_way;
	}

   // 默认搜索货品名称
   //special_pk 是方便复合搜索,增加复杂ID,如搜索产品相关的关联视图, Product.id 即可对视图搜索提供支持.
	public function search($words,$model_name = 'Product',$search_field="name",$special_pk=""){
		$model = D($model_name);
		$pk = $model->getPk ();

		if(empty($words))
			return ;
		$words = $this->formatWords($words);
		$Product = empty($model_name)? M('Product') : $model;
		$result = array();
		
		foreach ($words as $key=>$value) {
			$map = array(
				$search_field => array('like','%'.$value.'%'),
			);
		$data = $Product->where($map)->field($pk)->findAll();
		if($key == 0){
			$result = $this->change2array($data);
			continue;
		}
			
		$result = array_unique(array_intersect($result, $this->change2array($data) ));
		}
		
        if(!empty($special_pk))
            $pk = $special_pk;
		$res_map[$pk]= array('in',implode(',', $result) );
		return $res_map;
		//TODO 可返回查询结果或查询过滤数组
		//$end_result = $Product->where('id in('.implode(',', $result).')')->findAll();
		//return $end_result;
	}
}

?>
